<template>
  <div>
    <a-table
      ref="table"
      :loading="loading"
      :pagination="false"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :expanded-row-keys="expandedRowKeys"
      :columns="mainColumns"
      :data-source="mainData"
      row-key="id"
      @expand="expandedRowsChange"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <a-table
        slot="expandedRowRender"
        slot-scope="text"
        :loading="childLoading"
        :row-selection="state !== 3 ? { selectedRowKeys: childSelectedRowKeys, onChange: childChange ,type:'radio'}:null"
        row-key="id"
        :columns="childColumns"
        :data-source="data"
        :pagination="false"
      >
        <span
          slot="index"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <template
          v-for="col in ['inTaxSmount', 'exTaxSmount']"
          :slot="col"
          slot-scope="text, row, index"
        >
          <div :key="col">
            <template v-if="row.editable">
              <BaseInputNumber
                :precision="2"
                :value="text"
                @blur="e => handleChange(e.target.value, row, col)"
              />
            </template>
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template
          slot="operation"
          slot-scope="text, row, index"
        >
          <div
            v-if="state !== 3"
            class="editable-row-operations"
          >
            <span v-if="row.editable ">
              <a @click="() => save(row.id)">保存</a>
              <a @click="cancel(row.id)">取消</a>
            </span>
            <span v-else>
              <a
                :disabled="editingKey !== ''"
                @click="() => edit(row)"
              >编辑</a>
            </span>
          </div>
        </template>
      </a-table>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <excel
      ref="exportSelect"
      file-name="物资维度"
      is-click-generate="false"
    >
      <span slot="excelBtn" />
    </excel>
  </div>
</template>
<script>
import { materialsMainList, materialsMainSupplierList, materialsMainEdit } from '@/api/material/procurement/sign'
import { mainColumns, childColumns } from './insideModel'

const data = []
export default {
	name:'a'+Date.now(),
    data: function() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            queryParam: {},
            loading: false,
            pageNo: 1,
            pageSize: 10,
            totalSize: 0,
            mainData: [],
            expandedRowKeys: [],
            data: [],
            mainColumns: mainColumns,
            childColumns: childColumns,
            selectedRowKeys: [],
            selectedRows: [],
            editingKey: '',
            childSelectedRowKeys: [],
            childLoading: false,
            childSelectRow: [],
            recordId: null
        }
    },
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    mounted() {
        this.list()
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$bus.$on('exportSelectMaterials', () => {
            this.exportSelect()
        })
    },
    methods: {
        exportSelect() {
            if (this.selectedRows.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        async childChange(selectedRowKeys, selectedRows) {
            this.childSelectRow = selectedRows[0]
            this.childSelectedRowKeys = selectedRowKeys
            this.childSelectRow.tenderFileReviewCountersignDetailsId = this.recordId
            this.childSelectRow.recommendWin = true


            let res = await materialsMainEdit(this.childSelectRow)
            if (res.code === 200 || res.data.code === 200) {
                this.$message.success('设为招标组推荐中标候选人成功')
                this.list()
            }
        },
        expandedRowsChange: function(expanded, record) {
            if (expanded) {
                this.childSelectedRowKeys = []
                this.childSelectRow = []
                this.expandedRowKeys = [record.id]
                this.recordId = record.id
                this.supplierList()
            } else {
                this.expandedRowKeys = []
            }
        },
        list(params, callback) {
            let _this = this
            let searchData = Object.assign({
                    pageSize: callback ? _this.totalSize : _this.pageSize
                    , pageNo: _this.pageNo,
                    countersignId: _this.id
                },
                params)
            this.loading = true
            materialsMainList(searchData).then(res => {
                if (res.code === 200 || res.data.code === 200) {
                    if (callback) {
                        if (res.data.length) {
                            callback(res.data)
                        } else {
                            this.$message.warning('没有可导出的数据')
                        }
                        this.loading = false
                        return
                    }
                    _this.mainData = res.data
                    _this.totalSize = res.totalSize
                }
                this.loading = false
            })
        },
        async supplierList(id) {
            this.childLoading = true
            let res = await materialsMainSupplierList({ id: this.recordId })
            if (res.code === 200 || res.data.code === 200) {
                this.data = res.data
                res.data.map(v => {
                    if (v.recommendWin) this.childSelectedRowKeys = [v.id]
                })
                this.cacheData = JSON.parse(JSON.stringify(this.data))
            }
            this.childLoading = false

        },
        search(val) {
            this.pageNo = 1
            this.queryParam = val
            this.list(val)
        },
        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
            this.selectedRowKeys = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageNo = 1
            this.pageSize = pageSize
            this.list()
        },
        onSelectChange(selectedRowKeys, selectedRows) {
            this.$console(selectedRows)
            this.selectedId = []
            selectedRows.map(i => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },
        edit(row) {
            const newData = [...this.data]
            this.editingKey = row.id
            row.editable = true
            this.data = newData
        },
        handleChange(value, row, column) {
            const newData = [...this.data]
            const target = newData.filter(item => row.id === item.id)[0]
            if (target) {
                target[column] = value
                this.data = newData
            }
        },
        save(key) {
            // 编辑保存
            const newData = [...this.data]
            const newCacheData = [...this.cacheData]
            const target = newData.filter(item => key === item.id)[0]
            target.tenderFileReviewCountersignDetailsId = this.recordId
            this.loading = true
            materialsMainEdit(target).then(res => {
                if (res.code === 200 || res.data.code === 200) {
                    this.$message.success('编辑成功')
                    this.supplierList()
                }
                this.loading = false
            })
            const targetCache = newCacheData.filter(item => key === item.id)[0]
            if (target && targetCache) {
                delete target.editable
                this.data = newData
                Object.assign(targetCache, target)
                this.cacheData = newCacheData
            }
            this.editingKey = ''
        },
        cancel(key) {
            const newData = [...this.data]
            const target = newData.filter(item => key === item.id)[0]
            this.editingKey = ''
            this.planDate = null
            this.selectVal = null
            if (target) {
                Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
                // target.editable = false;
                delete target.editable
                this.data = newData
            }
        }
    }
}
</script>
